package com.axend.aerosense.common.util;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseDevInfoBean;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.utils.EquipmentUtil;
import com.axend.aerosense.common.R;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.NoticeBean;
import com.axend.aerosense.common.bean.UpdateAppBean;
import com.axend.aerosense.common.bean.UserInfo;
import com.axend.aerosense.common.bean.VipRenewNoticeBean;
import com.axend.aerosense.common.bean.WindowNotice;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.ui.CustomUpdateDialog;
import com.axend.aerosense.common.ui.CustomVipRenewDialog;
import com.axend.aerosense.common.ui.NoticeDialog;
import com.axend.aerosense.common.ui.WebActivity;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import io.reactivex.disposables.Disposable;

public class CheckUpdateUtil {
    private Activity activity;//弹窗显示的Activity
    boolean isMainPage;//是否是首页
    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;
    private NoticeBean noticeBean;
    private NoticeDialog noticeDialog;

    public CheckUpdateUtil(Activity activity, boolean isMainPage) {
        this.activity = activity;
        this.isMainPage = isMainPage;
        ARouter.getInstance().inject(this);
    }

    /**
     * 检查更新方法
     */
    public void checkUpdate() {
//        Log.d("myTAG", "checkUpdate: 检查更新方法");
//        this.activity = activity;
        Disposable disposable = EasyHttp.post(UrlApi.URL.GetAppVersion.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<UpdateAppBean>() {
                    @Override
                    public void onTokenExpire() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(UpdateAppBean updateAppBean) {
                        String versionCode = "" + EquipmentUtil.getAppVersionNumber();
                        // 需要更新提示的 1. 客户端版本和服务器端不一致, 2.强制更新的, 3. 可跳过的版本号和已经跳过的版本号不一致
                        if (!TextUtils.isEmpty(updateAppBean.getServiceEdtion()) && !versionCode.equals(updateAppBean.getServiceEdtion())) {
                            String lastVersionCode = "" + MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.LAST_JUMP_VERSION, "");
                            if (updateAppBean.getState() == 0 && lastVersionCode.equals(updateAppBean.getServiceEdtion())) {
                                //3. 可跳过的版本号和已经跳过的版本号一致无需提示
                                getNotice();
                                return;
                            }
                            try {
                                if (TextUtils.isEmpty(updateAppBean.getServiceEdtion())
                                        || Integer.parseInt(versionCode) >= Integer.parseInt(updateAppBean.getServiceEdtion())) {
                                    if(!isMainPage){
                                        ToastUtils.showShort(R.string.common_new_version);
                                    }
                                    getNotice();
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            CustomUpdateDialog customUpdateDialog = new CustomUpdateDialog(activity, updateAppBean, false);
                            customUpdateDialog.setCancelable(false);
                            customUpdateDialog.setCanceledOnTouchOutside(false);

                            customUpdateDialog.setOnClickBottomListener(new CustomUpdateDialog.OnClickBottomListener() {
                                @Override
                                public void onPositiveClick() {

                                }

                                @Override
                                public void onNegtiveClick() {
                                    if (updateAppBean.getState() == 0) {
                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LAST_JUMP_VERSION, updateAppBean.getServiceEdtion());
                                        getNotice();
                                    }

                                }

                                @Override
                                public void onCloseClick() {
                                    if (updateAppBean.getState() == 0) {
                                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.LAST_JUMP_VERSION, updateAppBean.getServiceEdtion());
                                        getNotice();
                                    }
                                }
                            });
                            customUpdateDialog.show();
                        } else if (isMainPage) {
                            getNotice();
                        }
                    }
                });
    }

    //会员过期通知
    public void getVipRenewNotice() {
//        Log.d("myTAG", "getVipRenewNotice:会员过期通知 ");
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        if (TextUtils.isEmpty(token)) {
            return;
        }
        Disposable disposable = EasyHttp.post(UrlApi.URL.GetVipRenewNotice.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<VipRenewNoticeBean>() {
                    @Override
                    public void onTokenExpire() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(VipRenewNoticeBean vipRenewNoticeBean) {
                        if (vipRenewNoticeBean.operate) {
                            CustomVipRenewDialog customVipRenewDialog = new CustomVipRenewDialog(activity, vipRenewNoticeBean.daysRemaining);
                            customVipRenewDialog.show();
                        }
                    }
                });
    }

    /**
     * 首页广告弹窗（VIP过期提示公告）
     */
    public void getNotice() {
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        if (TextUtils.isEmpty(token)) {
            return;
        }
        String date = getNoticeDay();
        String tmp = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.NOTICE, "");
        if(date.equals(tmp)){
            // 控制弹窗次数, 一天一次
            return;
        }

        Disposable disposable = EasyHttp.post(UrlApi.URL.GetNotice.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<NoticeBean>() {
                    @Override
                    public void onTokenExpire() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(NoticeBean noticeBean) {
                        String date = getNoticeDay();
                        MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.NOTICE, date);
                        UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
                        if (null != userInfo && userInfo.userVipState != 1) {
                            // 非VIP 才弹出 广告
                            noticeDialog = new NoticeDialog(activity, noticeBean);
                            CheckUpdateUtil.this.noticeBean = noticeBean;
                            noticeDialog.setCancelable(false);
                            noticeDialog.setCanceledOnTouchOutside(false);
                            noticeDialog.setOnClickBottomListener(listener);
                            noticeDialog.show();
                        }else{
                            //是vip 检查天数
                            getVipRenewNotice();
                        }

                        //获取公告\通知
                        getWindowNotice();
                    }
                });
    }

    /**
     * 监听dialog关闭按钮
     */
    private NoticeDialog.OnClickBottomListener listener = new NoticeDialog.OnClickBottomListener() {

        @Override
        public void onPositiveClick() {
            if (null == noticeBean || null == noticeDialog) {
                return;
            }
            noticeDialog.dismiss();
            noticeDialog = null;
            if (noticeBean.noticeType == 0) {
                iLoginService.logout(activity, () -> {
                    MmkvHelper.getInstance().getMmkv().encode(Gobal.SAVE_KEY.NOTICE, "");
                    iLoginService.login();
                    activity.finish();
                });
            } else {
                Intent intent = new Intent(activity, WebActivity.class);
                intent.putExtra(WebActivity.URL, (String) noticeBean.noticeUrl);
                activity.startActivity(intent);
            }

        }

        @Override
        public void onCloseClick() {
            if (null == noticeDialog) {
                return;
            }
            noticeDialog.dismiss();
            noticeDialog = null;
        }
    };
    private String getNoticeDay(){
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;
    }

    /**
     * 获取公告信息
     */
    public void getWindowNotice(){
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        if (TextUtils.isEmpty(token)) {
            return;
        }

        Disposable disposable = EasyHttp.post(UrlApi.URL.GetWindowNotice.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<WindowNotice>() {
                    @Override
                    public void onTokenExpire() {

                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(WindowNotice bean) {
                        if (null == bean || bean.getNotice().getNoticeSwitch() == 0) return;

                        NoticeDialog dialog = new NoticeDialog(activity, bean.getNotice().getNoticeMsg());
                        dialog.setCancelable(false);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                    }
                });
    }
}
